import { app, BrowserWindow, ipcMain, screen } from "electron";
import { PATH } from "../utils";

export const startAppIpc = (win) => {
  ipcMain.on("move-application", (event, pos) => {
    win.setPosition(pos.posX, pos.posY);
  });

  ipcMain.on("maximize", (e) => win.maximize());

  ipcMain.on("load-page", (event, url, isFullScreen) => {
    const child = new BrowserWindow({
      parent: win,
      width: 1300 + 50,
      height: 800 + 50,
      frame: false,
    });
    child.loadURL(url);
    if (isFullScreen) {
      child.maximize();
    }
    win.child = child;
  });

  ipcMain.on("close-child", () => {
    if (win.child) {
      win.child.hide();
      win.show();
    }
  });

  ipcMain.on("open-Url", (event, arg) => {
    const width = screen.getPrimaryDisplay().size.width;
    const height = screen.getPrimaryDisplay().size.height;
    win.setContentSize(width, height); // 重新设置大小
    win.setFullScreen(true);
    win.setSimpleFullScreen(true);
  });

  ipcMain.on("back", (event, arg) => {
    win.setFullScreen(false);
    win.setSimpleFullScreen(false);
    win.setContentSize(1300 + 50, 800 + 50); // 重新设置大小
    win.center(); // 居中显示
  });

  ipcMain.on("minimizes", (event, arg) => {
    win.minimize();
  });

  ipcMain.on("backLogin", (event, arg) => {
    win.setFullScreen(false);
    win.setSimpleFullScreen(false);
    win.setContentSize(1300 + 50, 800 + 50); // 重新设置大小
    win.center(); // 居中显示
  });

  // 关闭应用(一次)
  ipcMain.once("close", (event, arg) => {
    app.quit();
  });

  // 应用启动
  ipcMain.handle("open-win", (event, arg) => {
    const childWindow = new BrowserWindow({
      webPreferences: {
        preload: PATH.preload,
        nodeIntegration: true,
      },
    });
    if (isDev()) {
      childWindow.loadFile(indexHtml, { hash: arg });
    } else {
      childWindow.loadURL(`${url}/#${arg}`);
    }
  });

  ipcMain.handle("getIconfontPath", (event, arg) => {
    return PATH.iconfont;
  });

  ipcMain.on("getAppCwd", (event, arg) => {
    event.returnValue = process.cwd();
  });
};
